package com.xiaozhen.blog.event;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaozhen.blog.entity.Event;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @create 2023-05-23 15:42
 * 生产者
 */
@Component
public class EventProducer {
    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 点赞
     * @param event
     */
    public void sendLikeMessage(Event event) throws JsonProcessingException {
        // 将实体类转换为 JSON 字符串
        String message = new ObjectMapper().writeValueAsString(event);
        // 发送消息
        rabbitTemplate.convertAndSend("exchange", "like", message);
    }

    /**
     * 发布评论
     * @param event
     */
    public void sendCommentMessage(Event event) throws JsonProcessingException {
        // 将实体类转换为 JSON 字符串
        String message = new ObjectMapper().writeValueAsString(event);
        // 发送消息
        rabbitTemplate.convertAndSend("exchange", "comment", message);
    }

    public void sendFollowMessage(String message) {
        rabbitTemplate.convertAndSend("exchange", "follow", message);
    }
}
